package com.bingo.mpa.portal;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.express.portal.ActionContext;
import org.express.portal.HttpUtils;
import org.express.portal.Mapping;
import org.express.portal.MultipartHttpServletRequest;
import org.express.portal.PathUtil;
import org.express.portal.Utils;
import org.express.portal.persist.QueryHelper;
import org.express.portal.renderer.RedirectRenderer;
import org.express.portal.renderer.Renderer;
import org.express.portal.renderer.TemplateRenderer;
import org.express.portal.renderer.TextRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bingo.mpa.pojo.Kong;
import com.bingo.mpa.pojo.Log;
import com.bingo.mpa.pojo.Order;
import com.bingo.mpa.service.LogService;
import com.bingo.mpa.util.Common;
import com.bingo.mpa.util.HttpClient;
import com.bingo.mpa.util.Tools;
import com.bingo.mpa.vo.Msg;
import com.bingo.mpa.vo.Pack;
import com.bingo.mpa.vo.kc.Header;
import com.bingo.mpa.vo.kc.KongCVO;

public class Sale
{
	private final Logger log = LoggerFactory.getLogger(getClass());
	
	/**
	 * 跳转到选号码页面(3G和全球通)
	 * @param carrier
	 * @return
	 */
	@Mapping("/phone/$1")
	public Renderer phone(int carrier)
	{
		log.info("carrier="+carrier);
		Map<String,Object> model = new HashMap<String,Object>();
		model.put("carrier", carrier);
		try
		{
			String token = HttpUtils.getCookie("mpa_token");
			String sql = "SELECT * FROM P_USER WHERE TOKEN=?";
			if(token == null)
			{
				return new RedirectRenderer("/login");
			}
			com.bingo.mpa.pojo.User user = QueryHelper.read_cache(com.bingo.mpa.pojo.User.class, "user", token, sql, new Object[]{token});
			if(user == null)
			{
				return new RedirectRenderer("/login");
			}
			switch(carrier)
			{
				case 1:
					model.put("carrierName", "中国移动");
					break;
				case 2:
					model.put("carrierName", "中国联通");
					break;
				case 3:
					model.put("carrierName", "中国电信");
					break;
				default:
					//干掉cookie重新登录
					HttpUtils.removeCookie("mpa_token","/");
					return new RedirectRenderer("/login");
			}
			int min = HttpUtils.getIntParameter("min", -1);
			int max = HttpUtils.getIntParameter("max", -1);
			String start = HttpUtils.getStringParameter("start","");
			String end = HttpUtils.getStringParameter("end","");
			String keyword = HttpUtils.getStringParameter("keyword");
			keyword = Tools.replaceStr(keyword);
			byte brand = 10;
			if(carrier == 1)brand = 10;
			else if(carrier == 2)brand = 20;
			
			List<Object> ll = new ArrayList<Object>();
			StringBuffer sqll = new StringBuffer("SELECT COUNT(PID) FROM P_PHONE WHERE STATUS=1 AND CARRIER=" +carrier+" AND BRAND="+brand);
			if(min >0)
			{
				sqll.append(" AND RETAIL >=?");
				ll.add(min*100);
			}
			if(max >0)
			{
				sqll.append(" AND RETAIL <=?");
				ll.add(max*100);
			}
			if(start != null && start.length()>0)
			{
				sqll.append(" AND PHONE LIKE '"+start+"%'");
			}
			if(end != null && end.length()>0)
			{
				sqll.append(" AND PHONE LIKE '%"+end+"'");
			}
			if(keyword != null && keyword.length()>0)
			{
				sqll.append(" AND PHONE LIKE '%"+keyword+"'");
			}
			Object[] param = new Object[ll.size()];
			ll.toArray(param);
			long count = QueryHelper.stat(sqll.toString(), param);
			if(min>0)
				model.put("min", min);
			if(max>0)
				model.put("max", max);
			model.put("start", start);
			model.put("end", end);
			model.put("keyword", keyword);
			model.put("count", count);
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TemplateRenderer("/phonev2.html","model",model);
	}
	
	@Mapping("/phone/page/$1")
	public Renderer phone_page(int carrier)
	{
		StringBuilder sb = new StringBuilder();
		try
		{
			int page = HttpUtils.getIntParameter("page",1);
			int pageSize = HttpUtils.getIntParameter("pageSize", 9);
			
			int min = HttpUtils.getIntParameter("min", -1);
			int max = HttpUtils.getIntParameter("max", -1);
			String start = HttpUtils.getStringParameter("start","");
			String end = HttpUtils.getStringParameter("end","");
			String keyword = HttpUtils.getStringParameter("keyword");
			keyword = Tools.replaceStr(keyword);
			byte brand = 10;
			if(carrier == 1)brand = 10;
			else if(carrier == 2)brand = 20;
			
			List<Object> ll = new ArrayList<Object>();
			StringBuffer sql = new StringBuffer("SELECT * FROM P_PHONE WHERE STATUS=1 AND CARRIER=" +carrier+" AND BRAND="+brand);
			if(min >0)
			{
				sql.append(" AND RETAIL >=?");
				ll.add(min*100);
			}
			if(max >0)
			{
				sql.append(" AND RETAIL <=?");
				ll.add(max*100);
			}
			if(start != null && start.length()>0)
			{
				sql.append(" AND PHONE LIKE '"+start+"%'");
			}
			if(end != null && end.length()>0)
			{
				sql.append(" AND PHONE LIKE '%"+end+"'");
			}
			if(keyword != null && keyword.length()>0)
			{
				sql.append(" AND PHONE LIKE '%"+keyword+"'");
			}
			sql.append(" ORDER BY PID");
			Object[] param = new Object[ll.size()];
			ll.toArray(param);
			
			List<com.bingo.mpa.pojo.Phone> list = QueryHelper.query_slice(com.bingo.mpa.pojo.Phone.class, sql.toString(), page, pageSize,param);
			
			NumberFormat currentFormat=NumberFormat.getCurrencyInstance(Locale.CHINA);
			com.bingo.mpa.pojo.Phone obj = null;
			int p = list.size()/12;
			sb.append("<tr>");
			for(int t = 0; t<4;t++)
			{
				sb.append("<td valign=\"top\" width=\"25%\">");
				sb.append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"datatab\">");
				for(int i = t*12; i<(t+1)*12 && i<list.size();i++)
				{
					obj = list.get(i);
					sb.append("<tr id=\"tip"+obj.getPid()+"\" onclick=\"ri(this,"+obj.getPid()+");\" ondblclick=\"dblc(this,"+obj.getPid()+");\">");
					byte ct = obj.getCard_type();
					String num = ct ==1?"num1":ct==2?"num2":ct==3?"num3":"";
					sb.append("<td class=\""+num+"\">");
					sb.append(obj.getPhone().substring(0, 7));
					sb.append("<span class=\"orange\">&nbsp;"+obj.getPhone().substring(7)+"</span>");
					sb.append("</td><td>");
					sb.append(currentFormat.format(obj.getRetail()/100.0));
					sb.append("</td></tr>");
				}
				if(list.size()<(t+1)*12)
				{
					if(t ==p)
					{
						for(int j = 0;j<(t+1)*12-list.size();j++)
						{
							sb.append("<tr><td>&nbsp;");
							sb.append("</td><td>&nbsp;");
							sb.append("</td></tr>");
						}
					}
					else
					{
						for(int j = t*12;j<(t+1)*12;j++)
						{
							sb.append("<tr><td>&nbsp;");
							sb.append("</td><td>&nbsp;");
							sb.append("</td></tr>");
						}
					}
				}
				sb.append("</table></td>");
			}
			sb.append("</tr>");
			//log.info(sb.toString());
//			for(com.bingo.mpa.pojo.Phone obj :list)
//			{
//				sb.append("<tr><td class=\"num\" width=\"360\">");
//				sb.append(obj.getPhone().substring(0, 7));
//				sb.append("<span class=\"orange\">&nbsp;"+obj.getPhone().substring(7)+"</span>");
//				sb.append("</td><td>");
//				sb.append(currentFormat.format(obj.getRetail()/100.0));
//				sb.append("</td><td width=\"90\"><a href=\"#\" onclick=\"pick("+obj.getPid()+");\"><img src=\"/images/icon_buy.png\" width=\"20\" height=\"20\"/>");
//				sb.append("选择");
//				sb.append("</a></td></tr>");
//			}
//			if(list.size()<9)
//			{
//				for(int i = 0;i<9-list.size();i++)
//				{
//					sb.append("<tr><td width=\"120\">");
//					sb.append("</td><td>");
//					sb.append("</td><td>");
//					sb.append("</td></tr>");
//				}
//			}
			log.info(page+","+pageSize);
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TextRenderer(sb.toString());
	}
	
	/**
	 * 跳转到选号码页面(3G和全球通)
	 * @param carrier
	 * @return
	 */
	@Mapping("/2g/$1")
	public Renderer phone_2g(int brand)
	{
		log.info("brand="+brand);
		byte carrier = 1;
		if(brand == 11 || brand == 12)carrier = 1;
		else if(brand == 21 || brand == 22 || brand == 23)carrier = 2;
		Map<String,Object> model = new HashMap<String,Object>();
		model.put("brand", brand);
		try
		{
			String token = HttpUtils.getCookie("mpa_token");
			String sql = "SELECT * FROM P_USER WHERE TOKEN=?";
			if(token == null)
			{
				return new RedirectRenderer("/login");
			}
			com.bingo.mpa.pojo.User user = QueryHelper.read_cache(com.bingo.mpa.pojo.User.class, "user", token, sql, new Object[]{token});
			if(user == null)
			{
				return new RedirectRenderer("/login");
			}
			switch(carrier)
			{
				case 1:
					model.put("carrierName", "中国移动");
					break;
				case 2:
					model.put("carrierName", "中国联通");
					break;
				case 3:
					model.put("carrierName", "中国电信");
					break;
				default:
					//干掉cookie重新登录
					HttpUtils.removeCookie("mpa_token","/");
					return new RedirectRenderer("/login");
			}
			int min = HttpUtils.getIntParameter("min", -1);
			int max = HttpUtils.getIntParameter("max", -1);
			String start = HttpUtils.getStringParameter("start","");
			String end = HttpUtils.getStringParameter("end","");
			String keyword = HttpUtils.getStringParameter("keyword");
			keyword = Tools.replaceStr(keyword);
			
			List<Object> ll = new ArrayList<Object>();
			StringBuffer sqll = new StringBuffer("SELECT COUNT(PID) FROM P_PHONE WHERE STATUS=1 AND CARRIER=" +carrier+" AND BRAND="+brand);
			if(min >0)
			{
				sqll.append(" AND RETAIL >=?");
				ll.add(min*100);
			}
			if(max >0)
			{
				sqll.append(" AND RETAIL <=?");
				ll.add(max*100);
			}
			if(start != null && start.length()>0)
			{
				sqll.append(" AND PHONE LIKE '"+start+"%'");
			}
			if(end != null && end.length()>0)
			{
				sqll.append(" AND PHONE LIKE '%"+end+"'");
			}
			if(keyword != null && keyword.length()>0)
			{
				sqll.append(" AND PHONE LIKE '%"+keyword+"'");
			}
			Object[] param = new Object[ll.size()];
			ll.toArray(param);
			long count = QueryHelper.stat(sqll.toString(), param);
			if(min>0)
				model.put("min", min);
			if(max>0)
				model.put("max", max);
			model.put("start", start);
			model.put("end", end);
			model.put("keyword", keyword);
			model.put("count", count);
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TemplateRenderer("/phonev2_2g.html","model",model);
	}
	
	@Mapping("/2g/page/$1")
	public Renderer phone_2g_page(int brand)
	{
		StringBuilder sb = new StringBuilder();
		try
		{
			byte carrier = 1;
			if(brand == 11 || brand == 12 || brand == 41 || brand == 42 || brand ==71 || brand ==72)carrier = 1;
			else if(brand == 21 || brand == 22 || brand == 23 || brand == 81 || brand ==82)carrier = 2;
			
			int page = HttpUtils.getIntParameter("page",1);
			int pageSize = HttpUtils.getIntParameter("pageSize", 9);
			
			int min = HttpUtils.getIntParameter("min", -1);
			int max = HttpUtils.getIntParameter("max", -1);
			String start = HttpUtils.getStringParameter("start","");
			String end = HttpUtils.getStringParameter("end","");
			String keyword = HttpUtils.getStringParameter("keyword");
			keyword = Tools.replaceStr(keyword);
			List<Object> ll = new ArrayList<Object>();
			
			StringBuffer sql = new StringBuffer("SELECT * FROM P_PHONE WHERE STATUS=1 AND CARRIER=" +carrier+" AND BRAND="+brand);
			if(min >0)
			{
				sql.append(" AND RETAIL >=?");
				ll.add(min*100);
			}
			if(max >0)
			{
				sql.append(" AND RETAIL <=?");
				ll.add(max*100);
			}
			if(start != null && start.length()>0)
			{
				sql.append(" AND PHONE LIKE '"+start+"%'");
			}
			if(end != null && end.length()>0)
			{
				sql.append(" AND PHONE LIKE '%"+end+"'");
			}
			if(keyword != null && keyword.length()>0)
			{
				sql.append(" AND PHONE LIKE '%"+keyword+"'");
			}
			sql.append(" ORDER BY PID");
			Object[] param = new Object[ll.size()];
			ll.toArray(param);
			
			List<com.bingo.mpa.pojo.Phone> list = QueryHelper.query_slice(com.bingo.mpa.pojo.Phone.class, sql.toString(), page, pageSize,param);
			
			NumberFormat currentFormat=NumberFormat.getCurrencyInstance(Locale.CHINA);
			com.bingo.mpa.pojo.Phone obj = null;
			int p = list.size()/12;
			sb.append("<tr>");
			for(int t = 0; t<4;t++)
			{
				sb.append("<td valign=\"top\" width=\"25%\">");
				sb.append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"datatab\">");
				for(int i = t*12; i<(t+1)*12 && i<list.size();i++)
				{
					obj = list.get(i);
					sb.append("<tr id=\"tip"+obj.getPid()+"\" onclick=\"ri(this,"+obj.getPid()+");\" ondblclick=\"dblc(this,"+obj.getPid()+");\">");
					sb.append("<td class=\"num\">");
					sb.append(obj.getPhone().substring(0, 7));
					sb.append("<span class=\"orange\">&nbsp;"+obj.getPhone().substring(7)+"</span>");
					sb.append("</td><td>");
					sb.append(currentFormat.format(obj.getRetail()/100.0));
					sb.append("</td></tr>");
				}
				if(list.size()<(t+1)*12)
				{
					if(t ==p)
					{
						for(int j = 0;j<(t+1)*12-list.size();j++)
						{
							sb.append("<tr><td>&nbsp;");
							sb.append("</td><td>&nbsp;");
							sb.append("</td></tr>");
						}
					}
					else
					{
						for(int j = t*12;j<(t+1)*12;j++)
						{
							sb.append("<tr><td>&nbsp;");
							sb.append("</td><td>&nbsp;");
							sb.append("</td></tr>");
						}
					}
				}
				sb.append("</table></td>");
			}
			sb.append("</tr>");
			//log.info(sb.toString());
			log.info(page+","+pageSize);
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TextRenderer(sb.toString());
	}
	
	/**
	 * Ajax调用，检查号码是否已被其它人选中
	 * @return
	 */
	@Mapping("/sale/check")
	public Renderer phone_check()
	{
		Msg msg = new Msg();
		try
		{
			long pid = HttpUtils.getIntParameter("pid",0);
			String sql = "SELECT * FROM P_PHONE WHERE STATUS=1 AND PID=?";
			com.bingo.mpa.pojo.Phone phone = QueryHelper.get(com.bingo.mpa.pojo.Phone.class, sql, new Object[]{pid});
			if(phone == null)
			{
				msg.setMsg("false");
				return new TextRenderer(com.alibaba.fastjson.JSON.toJSONString(msg),"utf-8");
			}
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		msg.setMsg("true");
		log.info(com.alibaba.fastjson.JSON.toJSONString(msg),"utf-8");
		return new TextRenderer(com.alibaba.fastjson.JSON.toJSONString(msg),"utf-8");
	}
	
	@Mapping("/sale/cancle")
	public Renderer phone_cancle()
	{
		Msg msg = new Msg();
		try
		{
			long pid = HttpUtils.getIntParameter("pid",0);
			if(pid > 0)
			{
				String _update = "UPDATE P_PHONE SET STATUS=1 WHERE PID=?";
				QueryHelper.update(_update, new Object[]{pid});
			}
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		msg.setMsg("true");
		return new TextRenderer(com.alibaba.fastjson.JSON.toJSONString(msg),"utf-8");
	}
	
	/**
	 * 跳转到选套餐页面
	 * @return
	 */
	@Mapping("/package")
	public Renderer _package()
	{
		Map<String,Object> model = new HashMap<String,Object>();
		try
		{
			long pid = HttpUtils.getIntParameter("pid",0);
			int carrier = HttpUtils.getIntParameter("carrier", 0);
			log.info("pid="+pid+",carrier="+carrier);
			switch(carrier)
			{
				case 1:
					model.put("carrierName", "中国移动");
					break;
				case 2:
					model.put("carrierName", "中国联通");
					break;
				case 3:
					model.put("carrierName", "中国电信");
					break;
				default:
					//干掉cookie重新登录
					HttpUtils.removeCookie("mpa_token","/");
					return new RedirectRenderer("/login");
			}
			model.put("carrier", carrier);
			String sql = "SELECT * FROM P_PHONE WHERE STATUS=1 AND PID=?";
			com.bingo.mpa.pojo.Phone phone = QueryHelper.get(com.bingo.mpa.pojo.Phone.class, sql, new Object[]{pid});
			if(phone == null)
			{
				log.error("号码已被其他用户选了，返回再选一个吧");
				model.put("error", 1);
				
				String keyword = HttpUtils.getStringParameter("keyword");
				keyword = Tools.replaceStr(keyword);
				StringBuffer sqll = new StringBuffer("SELECT COUNT(PID) FROM P_PHONE WHERE STATUS=1 AND CARRIER=" +carrier);
				if(keyword != null && keyword.length()>0)
				{
					sqll.append(" AND PHONE LIKE '%"+keyword+"%'");
				}
				List<Object> ll = new ArrayList<Object>();
				Object[] param = new Object[ll.size()];
				ll.toArray(param);
				long count = QueryHelper.stat(sqll.toString(), param);
				
				model.put("count", count);
				return new TemplateRenderer("/phonev2.html","model",model);
			}
			//置为锁定
			String _update = "UPDATE P_PHONE SET STATUS=2,LOCK_TIME=? WHERE PID=?";
			QueryHelper.update(_update, new Object[]{Calendar.getInstance(Locale.CHINA).getTime(),pid});
			
			model.put("phone", phone);
			
			sql = "SELECT COUNT(PID) FROM P_PACKAGE WHERE CARRIER=" +carrier;
			long count = QueryHelper.stat(sql, new Object[]{});
			model.put("count", count);
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TemplateRenderer("/package.html","model",model);
	}
	
	@Mapping("/package/page/$1")
	public Renderer package_page(int carrier)
	{
		Pack pack = new Pack();
		StringBuilder sb = new StringBuilder();
		try
		{
			int page = HttpUtils.getIntParameter("page",1);
			int pageSize = HttpUtils.getIntParameter("pageSize", 9);
			
			//String[] types = new String[]{"A","B","C"};
			String[] types = new String[]{"A","B"};
			for(String type:types)
			{
				sb.setLength(0);
				StringBuffer sql = new StringBuffer("SELECT * FROM P_PACKAGE WHERE CARRIER=" +carrier+ " AND TYPE=?");
				List<com.bingo.mpa.pojo.Package> list = QueryHelper.query_cache(com.bingo.mpa.pojo.Package.class, "packages"+carrier+type,"packages"+carrier+type, sql.toString(), new Object[]{type});
				
				for(com.bingo.mpa.pojo.Package obj :list)
				{
					sb.append("<tr title=\""+obj.getContent_detail()+"\"><td width=\"90\">");
					sb.append(obj.getName());
					sb.append("</td><td width=\"60\">");
					sb.append(obj.getFee());
					sb.append("</td><td width=\"90\">");
					sb.append(obj.getVoice());
					sb.append("</td><td width=\"60\">");
					sb.append(obj.getTraffic());
					sb.append("</td><td width=\"150\">");
					sb.append(obj.getEx_voice());
					sb.append("</td><td width=\"120\">");
					sb.append(obj.getScope());
					sb.append("</td><td>");
					sb.append(obj.getContent());
					sb.append("</td><td id=\"p"+obj.getPid()+"\" width=\"160\" title=\""+obj.getPre_cont_detail()+"\" style=\"cursor:pointer;border-color:#0000FF;border-width:2px;border-style:solid;\" onmouseover=\"mover(this);\" onmouseout=\"mout(this);\" onclick=\"mao2(this);\">");
					sb.append(obj.getPre_content());
					sb.append("</td><td width=\"60\"><a href=\"javascript:void(0);\" onclick=\"pick("+obj.getPid()+","+obj.getCarrier()+");\"><img src=\"/images/icon_buy.png\" width=\"20\" height=\"20\"/>");
					sb.append("选择");
					sb.append("</a></td></tr>");
				}
				if(list.size()<9)
				{
					for(int i = 0;i<9-list.size();i++)
					{
						sb.append("<tr><td width=\"90\">");
						sb.append("</td><td>");
						sb.append("</td><td>");
						sb.append("</td><td>");
						sb.append("</td><td>");
						sb.append("</td><td>");
						sb.append("</td><td>");
						sb.append("</td><td>");
						sb.append("</td><td>");
						sb.append("</td></tr>");
					}
				}
				if(type.equalsIgnoreCase("A"))
				{
					pack.setA(sb.toString());
				}
				else if(type.equalsIgnoreCase("B"))
				{
					pack.setB(sb.toString());
				}
				else if(type.equalsIgnoreCase("C"))
				{
					pack.setC(sb.toString());
				}
			}
			log.info(page+","+pageSize);
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TextRenderer(com.alibaba.fastjson.JSON.toJSONString(pack),"utf-8");
	}
	
	/**
	 * 跳转到填写入网资料页面(3G或全球通)
	 * @return
	 */
	@Mapping("/aninfo")
	public Renderer aninfo()
	{
		Map<String,Object> model = new HashMap<String,Object>();
		try
		{
			int carrier = HttpUtils.getIntParameter("carrier", 0);	//运营商
			long pid = HttpUtils.getIntParameter("pid",0);			//号码
			int pack = HttpUtils.getIntParameter("pack", 0);		//套餐
			int tariffType = HttpUtils.getIntParameter("tariffType", 0);//入网当月资费处理方式
			
			//2013-09-25套餐分方案一和方案二，即是否要另外预存话费
			String prestore = HttpUtils.getStringParameter("prestore", "");
			log.info("carrier="+carrier+",pid="+pid+",pack="+pack+",tariffType="+tariffType+",prestore="+prestore);
			switch(carrier)
			{
				case 1:
					model.put("carrierName", "中国移动");
					break;
				case 2:
					model.put("carrierName", "中国联通");
					break;
				case 3:
					model.put("carrierName", "中国电信");
					break;
				default:
					//干掉cookie重新登录
					HttpUtils.removeCookie("mpa_token","/");
					return new RedirectRenderer("/login");
			}
			model.put("carrier", carrier);
			model.put("tariffType", tariffType);
			String sql = "SELECT * FROM P_PHONE WHERE STATUS=2 AND PID=?";
			com.bingo.mpa.pojo.Phone phone = QueryHelper.get(com.bingo.mpa.pojo.Phone.class, sql, new Object[]{pid});
			if(phone == null)
			{
				log.error("号码已被其他用户选了，返回再选一个吧");
				model.put("error", 1);
				
				String keyword = HttpUtils.getStringParameter("keyword");
				keyword = Tools.replaceStr(keyword);
				StringBuffer sqll = new StringBuffer("SELECT COUNT(PID) FROM P_PHONE WHERE STATUS=1 AND CARRIER=" +carrier);
				if(keyword != null && keyword.length()>0)
				{
					sqll.append(" AND PHONE LIKE '%"+keyword+"%'");
				}
				List<Object> ll = new ArrayList<Object>();
				Object[] param = new Object[ll.size()];
				ll.toArray(param);
				long count = QueryHelper.stat(sqll.toString(), param);
				
				model.put("count", count);
				return new TemplateRenderer("/phonev2.html","model",model);
			}
			model.put("phone", phone);
			
			//套餐
			sql = "SELECT * FROM P_PACKAGE WHERE PID=?";
			com.bingo.mpa.pojo.Package p = QueryHelper.get(com.bingo.mpa.pojo.Package.class, sql, new Object[]{pack});
			model.put("package", p);
			if(prestore != null && prestore.length()>0)
			{
				prestore = prestore.substring(1);
				if(prestore.equals(String.valueOf(pack)))
				{
					model.put("prestore", true);
				}
			}
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TemplateRenderer("/aninfo.html","model",model);
	}
	
	/**
	 * 跳转到填写入网资料页面(2G)
	 * @return
	 */
	@Mapping("/aninfo/2g")
	public Renderer aninfo_2g()
	{
		Map<String,Object> model = new HashMap<String,Object>();
		try
		{
			long pid = HttpUtils.getIntParameter("pid",0);			//号码
			int brand = HttpUtils.getIntParameter("brand", 0);		//品牌
			log.info("pid="+pid+",brand="+brand);
			
			byte carrier = 1;
			if(brand == 11 || brand == 12 || brand == 41 || brand == 42 || brand == 71 || brand == 72)carrier = 1;
			else if(brand == 21 || brand == 22 || brand == 23 || brand == 81 || brand == 82)carrier = 2;
			switch(carrier)
			{
				case 1:
					model.put("carrierName", "中国移动");
					break;
				case 2:
					model.put("carrierName", "中国联通");
					break;
				case 3:
					model.put("carrierName", "中国电信");
					break;
				default:
					//干掉cookie重新登录
					HttpUtils.removeCookie("mpa_token","/");
					return new RedirectRenderer("/login");
			}
			model.put("brand", brand);
			String sql = "SELECT * FROM P_PHONE WHERE STATUS=1 AND PID=?";
			com.bingo.mpa.pojo.Phone phone = QueryHelper.get(com.bingo.mpa.pojo.Phone.class, sql, new Object[]{pid});
			if(phone == null)
			{
				log.error("号码已被其他用户选了，返回再选一个吧");
				model.put("error", 1);
				
				String keyword = HttpUtils.getStringParameter("keyword");
				keyword = Tools.replaceStr(keyword);
				StringBuffer sqll = new StringBuffer("SELECT COUNT(PID) FROM P_PHONE WHERE STATUS=1 AND CARRIER=" +carrier+" AND BRAND="+brand);
				if(keyword != null && keyword.length()>0)
				{
					sqll.append(" AND PHONE LIKE '%"+keyword+"%'");
				}
				List<Object> ll = new ArrayList<Object>();
				Object[] param = new Object[ll.size()];
				ll.toArray(param);
				long count = QueryHelper.stat(sqll.toString(), param);
				
				model.put("count", count);
				return new TemplateRenderer("/phonev2_2g.html","model",model);
			}
			model.put("phone", phone);
			
			//置为锁定
			String _update = "UPDATE P_PHONE SET STATUS=2,LOCK_TIME=? WHERE PID=?";
			QueryHelper.update(_update, new Object[]{Calendar.getInstance(Locale.CHINA).getTime(),pid});
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TemplateRenderer("/aninfo_2g.html","model",model);
	}
	
	/**
	 * 提交订单(3G或全球通)
	 * @return
	 */
	@Mapping("/sale/post")
	public Renderer post()
	{
		String token = HttpUtils.getCookie("mpa_token");
		String sql = "SELECT * FROM P_USER WHERE TOKEN=?";
		if(token == null)
		{
			return new RedirectRenderer("/login");
		}
		com.bingo.mpa.pojo.User user = QueryHelper.read_cache(com.bingo.mpa.pojo.User.class, "user", token, sql, new Object[]{token});
		if(user == null)
		{
			return new RedirectRenderer("/login");
		}
		
		Msg msg = new Msg();
		int carrier = HttpUtils.getIntParameter("carrier", 0);	//运营商
		long pid = HttpUtils.getIntParameter("pid",0);			//号码
		long pack = HttpUtils.getIntParameter("pack", 0);		//套餐
		int tariffType = HttpUtils.getIntParameter("tariffType", 0);//入网当月资费处理方式
		String prestore = HttpUtils.getStringParameter("prestore", "");
		log.info("carrier="+carrier+",pid="+pid+",pack="+pack+",tariffType="+tariffType+",prestore="+prestore);
		
		//form
		String account_name = HttpUtils.getStringParameter("account_name");
		String id_number = HttpUtils.getStringParameter("id_number");
		String id_address = HttpUtils.getStringParameter("id_address");
		String _id_exp_date = HttpUtils.getStringParameter("id_exp_date");
		String tel = HttpUtils.getStringParameter("tel");
		String c_address = HttpUtils.getStringParameter("c_address");
		String iccid = HttpUtils.getStringParameter("iccid");
		
		sql = "SELECT * FROM P_PHONE WHERE STATUS=2 AND PID=?";
		com.bingo.mpa.pojo.Phone phone = QueryHelper.get(com.bingo.mpa.pojo.Phone.class, sql, new Object[]{pid});
		
		sql = "SELECT * FROM P_PACKAGE WHERE PID=?";
		com.bingo.mpa.pojo.Package pg = QueryHelper.get(com.bingo.mpa.pojo.Package.class, sql, new Object[]{pack});
		
		String clientIp = ActionContext.getActionContext().getHttpServletRequest().getRemoteAddr();
		try
		{
			HttpServletRequest request = ActionContext.getActionContext().getHttpServletRequest();
			InputStream input = null;
			String id_card = null;
			if (request instanceof MultipartHttpServletRequest)
			{
				MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
				input = multipartRequest.getFileInputStream("fileField");
				String fx = HttpUtils.getStringParameter("textfield");
				byte[] payload = org.apache.commons.io.IOUtils.toByteArray(input);
				File app = PathUtil.getAppPath();
				File file = new File(app,"data");
				file = new File(file,"order");
				String prefix = org.apache.commons.lang.time.DateFormatUtils.format(Calendar.getInstance(Locale.CHINA), "yyyyMMdd");
				file = new File(file,prefix);
				if(!file.exists())
				{
					file.mkdirs();
				}
				file = new File(file,pid+fx.substring(fx.lastIndexOf(".")));
				OutputStream output = new FileOutputStream(file);
				org.apache.commons.io.IOUtils.write(payload, output);
				org.apache.commons.io.IOUtils.closeQuietly(input);
				org.apache.commons.io.IOUtils.closeQuietly(output);
				
				String ph = file.getPath();
				id_card = ph.substring(ph.indexOf("order")).replaceAll("\\\\", "\\/");
			}
			if(phone != null && pg != null)
			{
				Order order = new Order();
				order.setAid(user.getAid());
				order.setSid(user.getSid());
				order.setS_account(user.getAccount());
				order.setCarrier(phone.getCarrier());
				order.setBrand(phone.getBrand());
				order.setCard_type(phone.getCard_type());
				order.setPhone(phone.getPhone());
				order.setPackage_(pg.getPid());
				order.setTariff_type((byte)tariffType);
				order.setRetail(phone.getRetail());
				order.setDiscount(phone.getDiscount());
				if(prestore.equalsIgnoreCase("true"))
				{
					order.setPrestore(pg.getPrestore()*100);
				}
				order.setProvince(phone.getProvince());
				order.setCity(phone.getCity());
				order.setStatus((byte)1);
				order.setAccount_name(account_name);
				order.setId_number(id_number);
				order.setId_address(id_address);
				order.setId_card(id_card);
				order.setIccid(iccid);
				java.util.Date id_exp_date = org.apache.commons.lang.time.DateUtils.parseDate(_id_exp_date, new String[]{"yyyy-MM-dd"});
				order.setId_exp_date(new java.sql.Timestamp(id_exp_date.getTime()));
				order.setTel(tel);
				order.setC_address(c_address);
				order.setOrder_time(new java.sql.Timestamp(Calendar.getInstance(Locale.CHINA).getTimeInMillis()));
				
				order.save();
				//置为已开卡
				String _update = "UPDATE P_PHONE SET STATUS=3,ACTIVE_TIME=? WHERE PID=?";
				QueryHelper.update(_update, new Object[]{Calendar.getInstance(Locale.CHINA).getTime(),pid});
				
				//写日志
				Log log = new Log(clientIp,(byte)1,(byte)1,"工号为"+user.getAccount()+"的营业员申请开卡，号码为"+phone.getPhone()+"，开卡姓名为"+account_name);
				LogService.getInstance().write(log);
			}
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		msg.setMsg("true");
		return new TextRenderer(com.alibaba.fastjson.JSON.toJSONString(msg),"utf-8");
	}
	
	/**
	 * 提交订单(2G)
	 * @return
	 */
	@Mapping("/post/2g")
	public Renderer post_2g()
	{
		String token = HttpUtils.getCookie("mpa_token");
		String sql = "SELECT * FROM P_USER WHERE TOKEN=?";
		if(token == null)
		{
			return new RedirectRenderer("/login");
		}
		com.bingo.mpa.pojo.User user = QueryHelper.read_cache(com.bingo.mpa.pojo.User.class, "user", token, sql, new Object[]{token});
		if(user == null)
		{
			return new RedirectRenderer("/login");
		}
		
		Msg msg = new Msg();
		int carrier = HttpUtils.getIntParameter("carrier", 0);	//运营商
		long pid = HttpUtils.getIntParameter("pid",0);			//号码
		log.info("carrier="+carrier+",pid="+pid);
		
		//form
		String account_name = HttpUtils.getStringParameter("account_name");
		String id_number = HttpUtils.getStringParameter("id_number");
		String id_address = HttpUtils.getStringParameter("id_address");
		String _id_exp_date = HttpUtils.getStringParameter("id_exp_date");
		String tel = HttpUtils.getStringParameter("tel");
		String c_address = HttpUtils.getStringParameter("c_address");
		
		sql = "SELECT * FROM P_PHONE WHERE STATUS=2 AND PID=?";
		com.bingo.mpa.pojo.Phone phone = QueryHelper.get(com.bingo.mpa.pojo.Phone.class, sql, new Object[]{pid});
		
		String clientIp = ActionContext.getActionContext().getHttpServletRequest().getRemoteAddr();
		try
		{
			HttpServletRequest request = ActionContext.getActionContext().getHttpServletRequest();
			InputStream input = null;
			String id_card = null;
			if (request instanceof MultipartHttpServletRequest)
			{
				MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
				input = multipartRequest.getFileInputStream("fileField");
				String fx = HttpUtils.getStringParameter("textfield");
				byte[] payload = org.apache.commons.io.IOUtils.toByteArray(input);
				File app = PathUtil.getAppPath();
				File file = new File(app,"data");
				file = new File(file,"order");
				String prefix = org.apache.commons.lang.time.DateFormatUtils.format(Calendar.getInstance(Locale.CHINA), "yyyyMMdd");
				file = new File(file,prefix);
				if(!file.exists())
				{
					file.mkdirs();
				}
				file = new File(file,pid+fx.substring(fx.lastIndexOf(".")));
				OutputStream output = new FileOutputStream(file);
				org.apache.commons.io.IOUtils.write(payload, output);
				org.apache.commons.io.IOUtils.closeQuietly(input);
				org.apache.commons.io.IOUtils.closeQuietly(output);
				
				String ph = file.getPath();
				id_card = ph.substring(ph.indexOf("order")).replaceAll("\\\\", "\\/");
			}
			if(phone != null)
			{
				Order order = new Order();
				order.setAid(user.getAid());
				order.setSid(user.getSid());
				order.setS_account(user.getAccount());
				order.setCarrier(phone.getCarrier());
				order.setBrand(phone.getBrand());
				order.setCard_type(phone.getCard_type());
				order.setPhone(phone.getPhone());
				order.setPackage_(0);
				order.setTariff_type((byte)0);
				order.setRetail(phone.getRetail());
				order.setDiscount(phone.getDiscount());
				order.setProvince(phone.getProvince());
				order.setCity(phone.getCity());
				order.setStatus((byte)1);
				order.setAccount_name(account_name);
				order.setId_number(id_number);
				order.setId_address(id_address);
				order.setId_card(id_card);
				order.setIccid("");
				java.util.Date id_exp_date = org.apache.commons.lang.time.DateUtils.parseDate(_id_exp_date, new String[]{"yyyy-MM-dd"});
				order.setId_exp_date(new java.sql.Timestamp(id_exp_date.getTime()));
				order.setTel(tel);
				order.setC_address(c_address);
				order.setOrder_time(new java.sql.Timestamp(Calendar.getInstance(Locale.CHINA).getTimeInMillis()));
				
				order.save();
				//置为已开卡
				String _update = "UPDATE P_PHONE SET STATUS=3,ACTIVE_TIME=? WHERE PID=?";
				QueryHelper.update(_update, new Object[]{Calendar.getInstance(Locale.CHINA).getTime(),pid});
				
				//写日志
				Log log = new Log(clientIp,(byte)1,(byte)1,"工号为"+user.getAccount()+"的营业员申请开卡，号码为"+phone.getPhone()+"，开卡姓名为"+account_name);
				LogService.getInstance().write(log);
			}
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		msg.setMsg("true");
		return new TextRenderer(com.alibaba.fastjson.JSON.toJSONString(msg),"utf-8");
	}
	
	/**
	 * 查询订单
	 * @return
	 */
	@Mapping("/sale/order")
	public Renderer sale_order()
	{
		Map<String,Object> model = new HashMap<String,Object>();
		try
		{
			String token = HttpUtils.getCookie("mpa_token");
			String sql = "SELECT * FROM P_USER WHERE TOKEN=?";
			if(token == null)
			{
				return new RedirectRenderer("/login");
			}
			com.bingo.mpa.pojo.User user = QueryHelper.read_cache(com.bingo.mpa.pojo.User.class, "user", token, sql, new Object[]{token});
			if(user == null)
			{
				return new RedirectRenderer("/login");
			}
			int carrier = HttpUtils.getIntParameter("carrier", -1);
			String dateType = HttpUtils.getStringParameter("dateType");
			String st = HttpUtils.getStringParameter("st");
			String et = HttpUtils.getStringParameter("et");
			if(dateType == null)
			{
				dateType = "today";
				st = Common.getMetaDate(dateType).getSt();
				et = Common.getMetaDate(dateType).getEt();
			}
			String keyword = HttpUtils.getStringParameter("keyword");
			keyword = Tools.replaceStr(keyword);
			log.info("carrier="+carrier+",dateType="+dateType+",st="+st+",et="+et+",keyword="+keyword);
			StringBuffer sqll = new StringBuffer("SELECT COUNT(OID) FROM P_ORDER WHERE S_ACCOUNT=?");
			List<Object> ll = new ArrayList<Object>();
			ll.add(user.getAccount());
			if(carrier != -1)
			{
				sqll.append(" AND CARRIER=?");
				ll.add(carrier);
			}
			if(st != null && st.length() > 0)
			{
				sqll.append(" AND ORDER_TIME >=?");
				java.util.Date _st = org.apache.commons.lang.time.DateUtils.parseDate(st, new String[]{"yyyy-MM-dd"});
				ll.add(_st);
			}
			if(et != null && et.length() > 0)
			{
				sqll.append(" AND ORDER_TIME <?");
				java.util.Date _et = org.apache.commons.lang.time.DateUtils.parseDate(et, new String[]{"yyyy-MM-dd"});
				ll.add(_et);
			}
			if(keyword != null && keyword.length()>0)
			{
				sqll.append(" AND PHONE LIKE '%"+keyword+"%'");
			}
			Object[] param = new Object[ll.size()];
			ll.toArray(param);
			long count = QueryHelper.stat(sqll.toString(), param);
			model.put("carrier", carrier);
			model.put("dateType", dateType);
			model.put("st", st);
			model.put("et", et);
			model.put("keyword", keyword);
			model.put("count", count);
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TemplateRenderer("/order_sale.html","model",model);
	}
	
	@Mapping("/order/page")
	public Renderer order_page()
	{
		StringBuilder sb = new StringBuilder();
		try
		{
			String token = HttpUtils.getCookie("mpa_token");
			String sql = "SELECT * FROM P_USER WHERE TOKEN=?";
			if(token == null)
			{
				return new RedirectRenderer("/login");
			}
			com.bingo.mpa.pojo.User user = QueryHelper.read_cache(com.bingo.mpa.pojo.User.class, "user", token, sql, new Object[]{token});
			if(user == null)
			{
				return new RedirectRenderer("/login");
			}
			
			int page = HttpUtils.getIntParameter("page",1);
			int pageSize = HttpUtils.getIntParameter("pageSize", 9);
			
			int carrier = HttpUtils.getIntParameter("carrier", -1);
			String st = HttpUtils.getStringParameter("st");
			String et = HttpUtils.getStringParameter("et");
			String keyword = HttpUtils.getStringParameter("keyword");
			keyword = Tools.replaceStr(keyword);
			List<Object> ll = new ArrayList<Object>();
			StringBuffer sqll = new StringBuffer("SELECT * FROM P_ORDER WHERE S_ACCOUNT=?");
			ll.add(user.getAccount());
			if(carrier != -1)
			{
				sqll.append(" AND CARRIER=?");
				ll.add(carrier);
			}
			if(st != null && st.length() > 0)
			{
				sqll.append(" AND ORDER_TIME >=?");
				java.util.Date _st = org.apache.commons.lang.time.DateUtils.parseDate(st, new String[]{"yyyy-MM-dd"});
				ll.add(_st);
			}
			if(et != null && et.length() > 0)
			{
				sqll.append(" AND ORDER_TIME <?");
				java.util.Date _et = org.apache.commons.lang.time.DateUtils.parseDate(et, new String[]{"yyyy-MM-dd"});
				ll.add(_et);
			}
			if(keyword != null && keyword.length()>0)
			{
				sqll.append(" AND PHONE LIKE '%"+keyword+"%'");
			}
			sqll.append(" ORDER BY ORDER_TIME DESC");
			Object[] param = new Object[ll.size()];
			ll.toArray(param);
			
			List<com.bingo.mpa.pojo.Order> list = QueryHelper.query_slice(com.bingo.mpa.pojo.Order.class, sqll.toString(), page, pageSize,param);
			
			sql = "SELECT * FROM P_PACKAGE";
			List<com.bingo.mpa.pojo.Package> lp = QueryHelper.query_cache(com.bingo.mpa.pojo.Package.class, "packages", "packages", sql, new Object[]{});
			Map<Integer,com.bingo.mpa.pojo.Package> map = new HashMap<Integer,com.bingo.mpa.pojo.Package>();
			if(lp != null && lp.size() > 0)
			{
				for(com.bingo.mpa.pojo.Package obj : lp)
				{
					map.put(Integer.valueOf(obj.getPid()), obj);
				}
			}
			NumberFormat currentFormat=NumberFormat.getCurrencyInstance(Locale.CHINA);
			com.bingo.mpa.pojo.Package tmp = null;
			for(com.bingo.mpa.pojo.Order obj :list)
			{
				sb.append("<tr><td width=\"22\">");
				sb.append("<input type=\"checkbox\" id=\"order"+obj.getOid()+"\" name=\"orderid\" value=\""+obj.getOid()+"\"/>");
				sb.append("</td><td width=\"110\">");
				sb.append(org.apache.commons.lang.time.DateFormatUtils.format(obj.getOrder_time(), "yyyy/MM/dd HH:mm"));
				sb.append("</td><td class=\"num16\" width=\"100\">");
				sb.append(obj.getPhone().substring(0, 7));
				sb.append("<span class=\"orange\">"+obj.getPhone().substring(7)+"</span>");
				sb.append("</td><td width=\"120\">");
				tmp = map.get(obj.getPackage_());
				if(tmp != null)
				{
					switch(tmp.getCarrier())
					{
						case 1:
							sb.append("<img src=\"/images/icon_mobile.png\"/>");
							break;
						case 2:
							sb.append("<img src=\"/images/icon_unicom.png\"/>");
							break;
					}
					sb.append(tmp.getName());
				}
				sb.append("</td><td width=\"60\">");
				sb.append(currentFormat.format(obj.getRetail()/100.0));
				sb.append("</td><td width=\"60\">");
				sb.append(currentFormat.format(obj.getPrestore()/100.0));
				sb.append("</td><td width=\"60\">");
				sb.append(obj.getStatus()==1?"<span style=\"color:red\">待开卡</span>":obj.getStatus()==2?"<span style=\"color:green\">已开卡</span>":obj.getStatus()==3?"<span style=\"color:blue\">已撤单</span>":obj.getStatus()==4?"<span style=\"color:red\">已驳回</span>":"未知");
				sb.append("</td><td width=\"50\">");
				sb.append(obj.getPay_status()==1?"<span style=\"color:red\">未支付</span>":obj.getPay_status()==2?"<span style=\"color:blue\">处理中</span>":obj.getPay_status()==3?"<span style=\"color:green\">已支付</span>":obj.getPay_status()==4?"<span style=\"color:red\">失败</span>":"未知");
				sb.append("</td><td>");
				sb.append(obj.getRemark()==null?"":obj.getRemark());
				String pack = tmp != null?tmp.getName():"无";
				sb.append("</td><td align=\"center\" width=\"60\"><a href=\"#\" onclick=\"detail("+obj.getOid()+",'"+pack+"');\">");
				sb.append("详情</a>|");
				sb.append("<a href=\"#\" onclick=\"payOne("+obj.getOid()+");\">支付</a>");
				sb.append("</td></tr>");
			}
			if(list.size()<9)
			{
				for(int i = 0;i<9-list.size();i++)
				{
					sb.append("<tr><td width=\"22\">");
					sb.append("</td><td>");
					sb.append("</td><td>");
					sb.append("</td><td>");
					sb.append("</td><td>");
					sb.append("</td><td>");
					sb.append("</td><td>");
					sb.append("</td><td>");
					sb.append("</td><td>");
					sb.append("</td><td>");
					sb.append("</td></tr>");
				}
			}
			log.info(page+","+pageSize);
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TextRenderer(sb.toString());
	}
	
	/**
	 * 订单详情
	 * @return
	 */
	@Mapping("/order/detail")
	public Renderer order_detail()
	{
		try
		{
			long oid = HttpUtils.getLongParameter("oid", -1);
			if(oid > 0)
			{
				String sql = "SELECT s.name,o.* FROM P_STORE s,P_ORDER o WHERE s.SID=o.SID AND o.OID=?";
				com.bingo.mpa.vo.OrderVO order = QueryHelper.get(com.bingo.mpa.vo.OrderVO.class, sql, new Object[]{oid});
				return new TextRenderer(com.alibaba.fastjson.JSON.toJSONString(order),"utf-8");
			}
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TextRenderer(com.alibaba.fastjson.JSON.toJSONString("error"),"utf-8");
	}
	
	/**
	 * 编辑订单信息
	 * @return
	 */
	@Mapping("/sale/order/mod")
	public Renderer order_modify()
	{
		Msg msg = new Msg();
		try
		{
			long oid = HttpUtils.getLongParameter("oid", -1);
			String account_name = HttpUtils.getStringParameter("account_name");
			String id_number = HttpUtils.getStringParameter("id_number");
			String id_address = HttpUtils.getStringParameter("id_address");
			String tel = HttpUtils.getStringParameter("tel");
			String c_address = HttpUtils.getStringParameter("c_address");
			String iccid = HttpUtils.getStringParameter("iccid");
			
			String phone = HttpUtils.getStringParameter("phone","");
			
			log.info("oid="+oid+",account_name="+account_name);
			if(oid > 0)
			{
				String sql = "UPDATE P_ORDER SET STATUS=1,ACCOUNT_NAME=?,ID_NUMBER=?,ID_ADDRESS = ?,TEL=?,C_ADDRESS=?,ICCID=? WHERE OID=?";
				QueryHelper.update(sql, new Object[]{account_name,id_number,id_address,tel,c_address,iccid,oid});
				msg.setMsg("true");
				
				//驳回的重新提交，号码状态由锁定改为已开卡
				String _update = "UPDATE P_PHONE SET STATUS=3,ACTIVE_TIME=? WHERE PHONE=?";
				if(phone.length()>0)
				QueryHelper.update(_update, new Object[]{Calendar.getInstance(Locale.CHINA).getTime(),phone});
				
				return new TextRenderer(com.alibaba.fastjson.JSON.toJSONString(msg),"utf-8");
			}
		}
		catch(Exception e)
		{
			log.error("",e);
		}
		return new TextRenderer(com.alibaba.fastjson.JSON.toJSONString("error"),"utf-8");
	}
	
	/**
	 * 联通空中充值
	 * @return
	 */
	@Mapping("/kc/unicom")
	public Renderer kc_unicom()
	{
		String token = HttpUtils.getCookie("mpa_token");
		String sql = "SELECT * FROM P_USER WHERE TOKEN=?";
		if(token == null)
		{
			return new RedirectRenderer("/login");
		}
		com.bingo.mpa.pojo.User user = QueryHelper.get(com.bingo.mpa.pojo.User.class, sql, new Object[]{token});
		if(user == null)
		{
			return new RedirectRenderer("/login");
		}
		StringBuffer url = new StringBuffer();
		try
		{
			long timestamp = System.currentTimeMillis();
			Properties kconf = new Properties();
			kconf.load(Sale.class.getResourceAsStream("/config/klksim.properties"));
			String keyStr = kconf.getProperty("unicom.inter.key");
			String syscode = kconf.getProperty("unicom.inter.syscode");
			url.append(kconf.getProperty("unicom.inter.url"));
			String u_token = String.format("xsxt_%1$tY%1$tm%1$td", new Date()) + Utils.getRandom(8);
			String key = Utils.encrypt(keyStr.getBytes(), u_token);
			
			Kong kong = new Kong();
			kong.setCarrier((byte)2);
			kong.setSyscode(syscode);
			kong.setToken(u_token);
			kong.setKey_(key);
			kong.setAccount(user.getAccount());
			kong.setReq_time(new java.sql.Timestamp(Calendar.getInstance(Locale.CHINA).getTimeInMillis()));
			kong.setReq_result((byte)0);
			kong.setReq_remark("success");
			long kid = kong.save();
			
			log.info("load properties cost "+ (System.currentTimeMillis()-timestamp));
			//调接口
			timestamp = System.currentTimeMillis();
			url.append("?systemcode="+syscode);
			url.append("&token="+u_token);
			url.append("&key="+key);
			log.info("call interface...");
			//String rsp = HttpClient.get(url.toString());
			log.info("send key to http://kc.szunicom.com cost " + (System.currentTimeMillis()-timestamp));
//			if(rsp != null)
//			{
				//KongCVO obj = JSON.parseObject(rsp,KongCVO.class);
//				if(obj != null && obj.getHeader()!=null)
//				{
//					log.info("call interface success");
//					sql = "UPDATE P_KC SET REQ_TIME=? ,REQ_RESULT=? ,REQ_REMARK=? WHERE KID=?";
//					QueryHelper.update(sql, new Object[]{new java.sql.Timestamp(Calendar.getInstance(Locale.CHINA).getTimeInMillis()),0,"success",kid});
//					
//					if(obj.getHeader().getCode()==0)
//					{
//						log.info("call interface success result = 0");
//						sql = "SELECT * FROM P_KC WHERE KID=?";
//						com.bingo.mpa.pojo.Kong tmp = QueryHelper.get(com.bingo.mpa.pojo.Kong.class, sql, new Object[]{kid});
//						long now = System.currentTimeMillis();
//						timestamp = now -timestamp;
//						while(true)
//						{
//							now = System.currentTimeMillis();
//							if(tmp.getRsp_time() != null || timestamp > 30000)
//							{
//								log.info("kong call me success or timeout");
//								break;
//							}
//							Thread.sleep(1000);
//							tmp = QueryHelper.get(com.bingo.mpa.pojo.Kong.class, sql, new Object[]{kid});
//							timestamp += System.currentTimeMillis()-now;
//						}
//					}
//				}
//			}
			return new RedirectRenderer(url.toString());
		}
		catch(Exception e)
		{
			log.error("failed to open kc ",e);
		}
		return new RedirectRenderer("http://kc.szunicom.com");
	}
	
	/**
	 * 空中充值平台回调接口
	 * @return
	 */
	@Mapping("/kc/service/u")
	public Renderer kc_service_unicom()
	{
		KongCVO vo = new KongCVO();
		Header header = new Header();
		header.setAlert(true);
		header.setCode(-1);
		header.setMessage("failed");
		
		try
		{
			log.info("callback...");
			String token = HttpUtils.getStringParameter("token","");
			String sql = "SELECT * FROM P_KC WHERE TOKEN=?";
			com.bingo.mpa.pojo.Kong tmp = QueryHelper.get(com.bingo.mpa.pojo.Kong.class, sql, new Object[]{token});
			if(tmp != null)
			{
				if(System.currentTimeMillis()-tmp.getReq_time().getTime() > 30000)
				{
					log.info("callback timeout...");
					header.setCode(1);
					header.setMessage("time out");
					vo.setBody("");
				}
				else
				{
					header.setCode(0);
					header.setMessage("success");
					vo.setBody(tmp.getAccount());
				}
				vo.setHeader(header);
				sql = "UPDATE P_KC SET RSP_TIME=? ,RSP_RESULT=? ,RSP_REMARK=? WHERE KID=?";
				QueryHelper.update(sql, new Object[]{new java.sql.Timestamp(Calendar.getInstance(Locale.CHINA).getTimeInMillis()),0,"success",tmp.getKid()});
			}
			else
			{
				vo.setHeader(header);
				vo.setBody("");
			}
		}
		catch(Exception e)
		{
			log.error("failed to open kc ",e);
		}
		return new TextRenderer(com.alibaba.fastjson.JSON.toJSONString(vo),"utf-8");
	}
}
